package com.ck.shardinggo.algorithm;

import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.RangeShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import io.shardingjdbc.core.api.algorithm.sharding.standard.RangeShardingAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.HashSet;

/**
 * @Author yd
 * @Date 2019/1/3 21:10
 */
@Slf4j
public class MyShardingConfig implements PreciseShardingAlgorithm, RangeShardingAlgorithm {

    /**
     * 精确分片算法
     * sex，如果小于等于5，数据对应的表为：t_user0
     * sex，如果大于5，数据对应的表为：t_user1
     * @param availableTargetNames
     * @param shardingValue
     * @return
     */
    @Override
    public String doSharding(Collection availableTargetNames, PreciseShardingValue shardingValue) {
            if(shardingValue.getColumnName().equalsIgnoreCase("sex")){
                Comparable value = shardingValue.getValue();
                int i = value.compareTo(5);
                int suffix = -1;
                if(i<=0){
                    suffix = 0;
                }else{
                    suffix = 1;
                }
                String s = ("t_user" + suffix);
                log.info("精确分片算法 [doSharding]:===============================> {}",s);
                return s;
            }
            return null;
    }

    /**
     * lower 为 between and 中的较小值
     * upper 为 between and 中的较大值
     * 如果lower小于等于5，tables集合中就要加入t_user0表
     * 如果lower大于5，tables集合中就要加入t_user1表
     * @param availableTargetNames
     * @param shardingValue
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection availableTargetNames, RangeShardingValue shardingValue) {

        Collection<String> tables = new HashSet<>();
        if(availableTargetNames.contains("t_user")){
            if(shardingValue.getColumnName().equalsIgnoreCase("sex")){
                Comparable lower = shardingValue.getValueRange().lowerEndpoint();
                Comparable upper = shardingValue.getValueRange().upperEndpoint();

                int lowerResult = lower.compareTo(5);
                int upperResult = upper.compareTo(5);

                if(lowerResult<=0){
                    tables.add("t_user_0".toUpperCase());
                    if(upperResult>0){
                        tables.add("t_user_2".toUpperCase());
                    }
                }else{
                    tables.add("t_user_2".toUpperCase());
                }
            }
        }
        return tables;
    }



}
